package espacokidsadm.modelo.dao.impl;

import java.util.List;

import javax.persistence.EntityTransaction;

import espacokidsadm.modelo.dao.Dao;
import espacokidsadm.modelo.entity.Aluno;
import espacokidsadm.modelo.entity.Responsavel;


public class AlunoDAO extends Dao {

	private static final long serialVersionUID = 1L;

	
	public Aluno salvar(Aluno aluno) {
		
		EntityTransaction transaction = getEm().getTransaction();
		transaction.begin();
		
		if(aluno.getId() == null){
			
			getEm().persist(aluno.getPessoa());
			salvarResposaveis(aluno.getResponsaveisAluno());
			getEm().persist(aluno);
			
		}else{
			
			getEm().merge(aluno.getPessoa());
			salvarResposaveis(aluno.getResponsaveisAluno());
			getEm().merge(aluno);
			
		}
		
		
		transaction.commit();
		
		return getById(aluno.getId());
		
	}

	
	private void salvarResposaveis(List<Responsavel> responsaveis){
		
		for(Responsavel responsavel : responsaveis){
			salvarResposavel(responsavel);
		}
		
	}
	
	private void salvarResposavel(Responsavel responsavel){
		
		if(responsavel.getId().getPessoa().getId() == null){
			getEm().persist(responsavel.getId().getPessoa());
		}else{
			getEm().merge(responsavel.getId().getPessoa());
		}
		
	}
	
	public Responsavel getResponsavelAlunoByCpf(String cpf){
		
		return getPojo(Responsavel.class, "from Responsavel resp where resp.id.pessoa.cpf = ?1", cpf);
		
	}
	
	public Aluno getById(Integer id) {
		
		return getPojo(Aluno.class, id);
		
	}

	
	public List<Aluno> getTodos() {
		
		//return getList(Aluno.class, "select aluno from Aluno aluno order by aluno.pessoa.nome");
		return getList(Aluno.class, "from Aluno aluno");
		
	}

}
